package com.atguigu.recursion;

/**
 * 使用递归回溯给小球找路
 * @author WangJX
 * @version 1.0
 * @date 2019/10/31 22:21
 */
public class MiGong {
    public static void main(String[] args) {
        int[][] map =new int[6][7];

        for (int i = 0; i < 6; i++) {
            map[0][i] = 1;
            map[5][i] = 1;
        }

        for (int i = 0; i < 6; i++) {
            map[i][0] = 1;
            map[i][6] = 1;
        }

        map[2][1] = 1;
        map[2][2] = 1;

        for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 7; j++) {
                System.out.print(map[i][j] + " ");
            }
            System.out.println();
        }

        setWay(map, 1, 1);

        System.out.println("走迷宫图：");
        for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 7; j++) {
                System.out.print(map[i][j] + " ");
            }
            System.out.println();
        }


    }

    /**
     * 使用递归+回溯的方法找到一条路
     * @param map
     * @param i
     * @param j
     * @return
     */
    public static boolean setWay(int[][] map, int i, int j) {
        if (map[4][5] == 2) {
            return true;
        } else {
            if (map[i][j] == 0) {
                map[i][j] = 2;
                //按照 下 -> 右 -> 上 -> 左 的规则找路径
                if (setWay(map, i + 1, j)) {
                    return true;
                } else if (setWay(map, i, j + 1)) {
                    return true;
                } else if (setWay(map, i - 1, j)) {
                    return true;
                } else if (setWay(map, i, j - 1)) {
                    return true;
                } else {
                    map[i][j] = 3;
                    return false;
                }
            } else {    //如果不等于0 则可能是1,2,3
                return false;
            }
        }
    }
}
